import { ref } from 'vue'
import { ElLoading } from 'element-plus'
import type { LoadingInstance } from 'element-plus/es/components/loading/src/loading'

// 全局加载状态管理
const globalLoading = ref(false)
let loadingInstance: LoadingInstance | null = null

export function useLoading() {
  const loading = ref(false)
  
  // 显示加载
  const showLoading = (text = '加载中...') => {
    loading.value = true
    globalLoading.value = true
    
    loadingInstance = ElLoading.service({
      lock: true,
      text,
      background: 'rgba(0, 0, 0, 0.7)'
    })
  }
  
  // 隐藏加载
  const hideLoading = () => {
    loading.value = false
    globalLoading.value = false
    
    if (loadingInstance) {
      loadingInstance.close()
      loadingInstance = null
    }
  }
  
  // 异步操作包装器
  const withLoading = async <T>(
    asyncFn: () => Promise<T>,
    loadingText = '处理中...'
  ): Promise<T> => {
    try {
      showLoading(loadingText)
      const result = await asyncFn()
      return result
    } finally {
      hideLoading()
    }
  }
  
  return {
    loading,
    globalLoading,
    showLoading,
    hideLoading,
    withLoading
  }
}